route.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { auth } from "../../auth";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. import { GEMINI_BASE_URL, Google } from "@/app/constant";
  5. async function handle(
  6. req: NextRequest,
  7. { params }: { params: { path: string[] } },
  8. ) {
  9. console.log("[Google Route] params ", params);
  10. if (req.method === "OPTIONS") {
  11. return NextResponse.json({ body: "OK" }, { status: 200 });
  12. }
  13. const controller = new AbortController();
  14. const serverConfig = getServerSideConfig();
  15. let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
  16. if (!baseUrl.startsWith("http")) {
  17. baseUrl = `https://${baseUrl}`;
  18. }
  19. if (baseUrl.endsWith("/")) {
  20. baseUrl = baseUrl.slice(0, -1);
  21. }
  22. let path = `${req.nextUrl.pathname}`.replaceAll("/api/google/", "");
  23. console.log("[Proxy] ", path);
  24. console.log("[Base Url]", baseUrl);
  25. // this fix [Org ID] undefined in server side if not using custom point
  26. if (serverConfig.openaiOrgId !== undefined) {
  27. console.log("[Org ID]", serverConfig.openaiOrgId);
  28. }
  29. const timeoutId = setTimeout(
  30. () => {
  31. controller.abort();
  32. },
  33. 10 * 60 * 1000,
  34. );
  35. const bearToken = req.headers.get("Authorization") ?? "";
  36. const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  37. const key = token ?? serverConfig.googleApiKey;
  38. const fetchUrl = `${baseUrl}/${path}?key=${key}`;
  39. const fetchOptions: RequestInit = {
  40. headers: {
  41. "Content-Type": "application/json",
  42. "Cache-Control": "no-store",
  43. },
  44. method: req.method,
  45. body: req.body,
  46. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  47. redirect: "manual",
  48. // @ts-ignore
  49. duplex: "half",
  50. signal: controller.signal,
  51. };
  52. try {
  53. const res = await fetch(fetchUrl, fetchOptions);
  54. // to prevent browser prompt for credentials
  55. const newHeaders = new Headers(res.headers);
  56. newHeaders.delete("www-authenticate");
  57. // to disable nginx buffering
  58. newHeaders.set("X-Accel-Buffering", "no");
  59. return new Response(res.body, {
  60. status: res.status,
  61. statusText: res.statusText,
  62. headers: newHeaders,
  63. });
  64. } finally {
  65. clearTimeout(timeoutId);
  66. }
  67. }
  68. export const GET = handle;
  69. export const POST = handle;
  70. export const runtime = "edge";
  71. export const preferredRegion = [
  72. "arn1",
  73. "bom1",
  74. "cdg1",
  75. "cle1",
  76. "cpt1",
  77. "dub1",
  78. "fra1",
  79. "gru1",
  80. "hnd1",
  81. "iad1",
  82. "icn1",
  83. "kix1",
  84. "lhr1",
  85. "pdx1",
  86. "sfo1",
  87. "sin1",
  88. "syd1",
  89. ];